<?php

namespace App\Services;

use App\Http\Resources\Home\OrderResource\CreateOrderAfterCollection;
use App\Jobs\SettlementShippingJob;
use App\Jobs\ShopIntegralJob;
use App\Models\Address;
use App\Models\Cart;
use App\Models\CouponLog;
use App\Models\Freight;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\OrderPay;
use App\Models\Property;
use App\Models\Refund;
use App\Models\Store;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderService extends BaseService
{

    use HelperTrait;

    public $addressService;
    public $user_info;

    public $integralService;

    /**
     * OrderService constructor.
     */
    public function __construct()
    {
        $this->user_info = new UserService();
        $this->addressService = new AddressService();
        $this->integralService = new IntegralSetService();
    }


    // 要删除的购物车数据
    protected $cartId = [];


    /**
     * // 支付订单 function
     *
     * @param string $order_id 如：10,12,13
     * @param string $payment_name 如：wechat_scan|balance|wechat_h5|wechat_mini
     * @param string $pay_password 如：123456 （非必填,payment_name=balance则需要填写)
     * @param string $recharge 如：1 （非必填）
     * @return void
     * @Description
     * @author hg <www.qingwuit.com>
     */
    public function payOrder(string $payment_name = 'wechat_mini')
    {
        $order_id = request()->order_id;

        // 检查支付方式是否传过来
        if (empty($payment_name)) {
            return $this->format_error(__('orders.empty_payment'));
        }
        // 判断订单号是否为空
        if (empty($order_id)) {
            return $this->format_error(__('orders.error') . ' - pay');
        }
        $order_arr = explode(',', $order_id); // 转化为数组
        $order_str = implode('', $order_arr); // 转化为字符串生成支付订单号
        // 获取用户信息
        $user_service = new UserService();
        $user_info = $user_service->getUserInfo();

        if (empty($user_info)) {
            return $this->format_error('请先登录');
        }

        // 判断是否订单是该用户的并且订单是否有支付成功过
        $order_model = new Order();
        // 判断是否存在 指定订单
        $data = $order_model->whereIn('id', $order_arr)->where('user_id', $user_info['id'])->exists();
        if (!$order_model->whereIn('id', $order_arr)->where('user_id', $user_info['id'])->exists()) {
            return $this->format_error(__('orders.error') . ' - pay2');
        }
        // 判断是否已经支付过了
        $order_list = $order_model->whereIn('id', $order_arr)->where('user_id', $user_info['id'])->where('order_status', 1)->get();
        if ($order_list->isEmpty()) {
            return $this->format_error(__('orders.order_pay'));
        }

        // 十秒钟不能重复支付 设计订单支付号 当前时间到秒的十位+用户ID+订单ID号
        $second = substr(date('YmdHis'), 0, 13);
        $pay_no = $second . $user_info['id'] . $order_str; // 订单支付号
        $rs = $this->createPayOrder(false, $user_info, $pay_no, $order_list);
        // 创建支付订单失败
        if (!$rs['status']) {
            return $this->format_error($rs['msg']);
        }

        // 获取支付信息,调取第三方支付
        $payment_model = new PayMentService();
        $rs = $payment_model->pay($payment_name, $rs['data']);

        return $rs['status'] ? $this->format($rs['data']) : $this->format_error($rs['msg']);
    }


    /**
     * 订单状态修改 function
     *
     * @param [type] $order_id 订单ID
     * @param [type] $order_status 订单状态
     * @param [type] $auth 用户操作还是管理员操作 user|admin
     * @return void
     * @Description
     * @author hg <www.qingwuit.com>
     */
    public function editOrderStatus($order_id, $order_status, $auth = "user")
    {
        $order_model = new Order;
        $order_model = $order_model->where('id', $order_id);
        if ($auth == 'user') {
            $user_service = new UserService;
            $user_info = $user_service->getUserInfo();
            if (empty($user_info)) {
                return $this->format_error(__('users.no_token'));
            }
            // 用户不允许随意操作状态，只能修改 取消订单和确定订单
            /*  if ($order_status != 0 && $order_status != 3) {
                  return $this->format_error(__('base.error'));
              }*/
            $order_model = $order_model->where('user_id', $user_info['id']);
        }
        $order_model = $order_model->first();
        if (empty($order_model)) {
            return $this->format_error(__('users.error_token'));
        }
        switch ($order_status) {
            case 0: // 取消订单
                if ($order_model->order_status != 1) { // 只有待支付的订单能取消
                    return $this->format_error(__('base.error') . ' - 0');
                }
                $og_model = new OrderGoods();
                $og_list = $og_model->select('goods_id', 'sku_id', 'buy_num')->where('order_id', $order_id)->get();
                foreach ($og_list as $v) {
                    $this->orderStock($v['goods_id'], $v['sku_id'], $v['buy_num'], 1);
                }
                $queue_data = [
                    'order_ids' => [$order_model->id],
                    'scenes_type' => 2,
                    'type' => 1,
                    'reward' => '取消订单积分原路返回',
                    'cllback' => true
                ];
                ShopIntegralJob::dispatch($queue_data)->onQueue('ShopIntegralJob');
                // 库存修改
                break;
            case 1: // 等待支付
                break;
            case 2: // 等待发货
                break;
            case 3: // 确认收货
                if (empty($order_model->delivery_no) || empty($order_model->delivery_code)) { //已发货订单可以确认收货
                    return $this->format_error(__('base.error') . ' - 3');
                }
                $queue_data = [
                    'order_ids' => [$order_model->id],
                    'scenes_type' => 2,
                    'type' => 1,
                    'reward' => '用户订单完成奖励积分',
                ];
                ShopIntegralJob::dispatch($queue_data)->onQueue('ShopIntegralJob');
                // 销量增加
                $og_model = new OrderGoods();
                $og_list = $og_model->select('goods_id', 'sku_id', 'buy_num')->where('order_id', $order_id)->get();
                foreach ($og_list as $v) {
                    $this->orderSale($v['goods_id'], $v['sku_id'], $v['buy_num'], 1);
                }
                //添加自动搜索
                $int = $this->getSettlementTime($order_model->community_id);
                $int = $int * 60;
                $settlement_data = [
                    'order_id' => $order_model->id,
                    'freight_money' => $order_model->freight_money
                ];
                SettlementShippingJob::dispatch($settlement_data)->onQueue('SettlementShippingJob')->delay($int);
                break;
            case 4: // 等待评论
                break;
            case 5: // 5售后
                break;
            case 6: // 6订单完成
                break;
        }
        $order_model->order_status = $order_status;
        $order_model->save();
        return $this->format([$order_status], __('base.success'));
    }


    /**
     * 2021/3/12--16:13
     * @param $order_id
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:OrderChangeAddress
     * @effect:用户修改地址
     */
    public function OrderChangeAddress($order_id)
    {
        $order_model = new Order;
        $order_model = $order_model->find($order_id);
        // 地址验证
        $address_resp = $this->checkAddress();
        if (!$address_resp['status']) {
            return $this->format_error($address_resp['msg']);
        }
        $address_info = $address_resp['data'];
        $order_model->receive_name = $address_info['receive_name']; // 收件人姓名
        $order_model->receive_tel = $address_info['receive_tel']; // 收件人电话
        $order_model->receive_area = $address_info['area_info']; // 收件人地区
        $order_model->receive_address = $address_info['address']; // 详细地址
        $order_model->address_id = $address_info['id']; // 详细地址
        $order_model->save();
        return $this->format([], __('base.success'));
    }




//------------------------------------------------------------------------订单创建相关------------------------------------//


    /**
     * 2021/3/11--11:00
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:createOrder
     * @effect:创建订单
     */
    public function createOrder()
    {

        $params['order'] = json_decode(request()->order, true);

        $rs = $this->createOrderFormat($params, false, false, false);
        if (!$rs['status']) {
            return $this->format_error($rs['msg']);
        }
        // 地址验证
        $address_resp = $this->checkAddress();
        if (!$address_resp['status']) {
            return $this->format_error($rs['msg']);
        }

        $address_info = $address_resp['data'];
        $user_service = new UserService;
        $user_info = $user_service->getUserInfo();

        if (empty($user_info)) {
            return $this->format_error(__('base.error') . ' - order_service');
        }
        // 实例化订单表
        $order_model = new Order();
        $order_goods_model = new OrderGoods();
        $full_reduction_service = new FullReductionService();

        // 循环生成订单 多个商家则生成多个订单
        try {
            DB::beginTransaction();
            $resp_data = [];
            foreach ($rs['data'] as $k => $v) {
                $make_rand = date('YmdHis') . $user_info['id'] . mt_rand(1000, 9999); // 生成订单号
                $order_data = [
                    'order_no' => $make_rand, // 订单号
                    'user_id' => $user_info['id'], // 用户ID
                    'store_id' => $v['store_info']['id'], // 店铺ID
                    'community_id' => $v['store_info']['community_id'],
                    'order_name' => $v['goods_list'][0]['goods_name'], // 商品ID
                    'order_image' => $v['goods_list'][0]['goods_master_image'], // 商品图片
                    'receive_name' => $address_info['receive_name'], // 收件人姓名
                    'receive_tel' => $address_info['receive_tel'], // 收件人电话
                    'receive_area' => $address_info['area_info'], // 收件人地区
                    'receive_address' => $address_info['address'], // 详细地址
                    'coupon_id' => isset($coupon_id[$k]) ? intval(abs($coupon_id[$k])) : 0, // 优惠券ID
                    'remark' => request()->remark ?? '', // 备注
                    'address_id' => request()->address_id ?? 0
                ];
                $order_info = $order_model->create($order_data);
                // 订单数据插入数据库
                // 初始化其他费用
                $total_price = 0; //订单总金额                                                                                                                                                                                                                                                                                                                                                                                                                          // 总金额
                $order_price = 0;  //订单金额                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             // 订单总金额
                $total_weight = 0; //商品总重量                                                                                                                                                                                                                                                                                                                 // 总重量
                $freight_money = 0;// 运费
                $integral_price = 0;//积分抵扣金额

                $coupon_money = 0; // 优惠券 金额
                // 循环将订单商品插入
                foreach ($v['goods_list'] as $vo) {
                    $order_goods_data = [
                        'order_id' => $order_info->id, // 订单ID
                        'user_id' => $order_info->user_id, // 用户ID
                        'store_id' => $order_info->store_id, // 店铺ID
                        'sku_id' => $vo['sku_id'], // skuid
                        'goods_id' => $vo['id'], // 商品id
                        'goods_name' => $vo['goods_name'], // 商品名称
                        'goods_image' => $vo['goods_master_image'], // 商品图片
                        'sku_name' => $vo['sku_name'], // sku名称
                        'buy_num' => $vo['buy_num'], // 购买数量
                        'goods_price' => $vo['goods_price'], // 商品价格
                        'total_price' => $vo['total'], // 总价格
                        'total_weight' => $vo['total_weight'], // 总重量
                    ];
                    $order_goods_model->create($order_goods_data); // 插入订单商品表
                    // 开始减去库存
                    $this->orderStock($order_goods_data['goods_id'], $order_goods_data['sku_id'], $order_goods_data['buy_num']);
                    // 将商品总总量加起来
                    $total_weight += $order_goods_data['total_weight'];
                    // 将金额全部计算加载到订单里面
                    $order_price += $order_goods_data['total_price'];
                }

                // 满减
                $full_reduction_resp = $full_reduction_service->getFullReductionInfoByStoreId($order_data['store_id'], ($order_price + $freight_money));
                if ($full_reduction_resp['status']) {
                    $coupon_money += $full_reduction_resp['data']['money'];
                }

                $storeService = new StoreService();
                $store_cate_id = $storeService->getStoreInfo($order_goods_data['store_id'])['data']['class_id'];
                // 积分抵扣

                $integral_discount_price = 0.00;
                $use_integral = 0.00;
                extract($this->integral_discount($order_goods_data['store_id'], 1, $store_cate_id), EXTR_OVERWRITE);
                $integral_price += $integral_discount_price;
                //不走快递所以注释
                /*  // 直接计算运费，如果多个不同的商品取第一个商品的运费
                  $freight_money = $this->sumFreight($v['goods_list']['0']['freight_id'], $total_weight, $order_data['store_id'], $address_info['province_id']);*/
                $freight_money = $this->getFreight($order_data['community_id']);
                // 暂时总金额等于[订单金额+运费-优惠金额]
                // 订单总金额做修改，然后保存
                $total_price = $order_price + $freight_money - $coupon_money;
                $order_info->total_price = round($total_price, 2);
                $order_info->order_price = $order_price;
                $order_info->freight_money = $freight_money;           // 运费
                $order_info->coupon_money = $coupon_money;             // 优惠金额修改
                $order_info->integral_price = $integral_price;         // 积分抵扣金额
                $order_info->use_integral = $use_integral;             //使用积分
                $order_info->save();                                   // 保存入数据库

                $queue_data = ['order_ids' => [$order_info->id], 'scenes_type' => 1, 'type' => 2, 'reward' => '用户下单扣除积分'];
                ShopIntegralJob::dispatch($queue_data)->onQueue('ShopIntegralJob');
                $resp_data['order_id'][] = $order_info->id;
                $resp_data['order_no'][] = $make_rand;
            }
            // 执行成功则删除购物车
            $this->delCart();
            DB::commit();
            // 多个订单 拼接成字符串
            $resp_data['order_id'] = implode(',', $resp_data['order_id']);
            $resp_data['order_no'] = implode(',', $resp_data['order_no']);
            return $this->format($resp_data);
        } catch (\Exception $e) {
            Log::channel('qwlog')->debug('createOrder:' . json_encode($e->getMessage()));
            DB::rollBack();
            return $this->format_error(__('orders.error') . $e->getMessage());
        }
    }


    /**
     * 2021/3/11--10:55
     * @param false $recharge_pay
     * @param $user_info
     * @param string $pay_no
     * @param array $order_list
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:createPayOrder
     * @effect:余额充值
     */
    protected function createPayOrder($recharge_pay = false, $user_info, $pay_no = '', $order_list = [])
    {
        // 创建支付订单
        $create_data = [];
        if ($recharge_pay) {
            $pay_no = date('YmdHis') . mt_rand(10000, 99999);
            $create_data = [
                'user_id' => $user_info['id'],
                'pay_no' => $pay_no,
                'pay_type' => 'r',
                'total_price' => abs(request()->total ?? 1), // 充值金额
            ];
        } else {
            $order_ids = [];
            $total_price = 0;
            $order_balance = 0;
            foreach ($order_list as $v) {
                $order_ids[] = $v['id'];
                $total_price += $v['total_price'];
                $order_balance += $v['order_balance'];
            }
            $create_data = [
                'user_id' => $user_info['id'],
                'pay_no' => $pay_no,
                'order_ids' => implode(',', $order_ids),
                'pay_type' => 'o',
                'total_price' => $total_price, // 订单总金额
                'order_balance' => $order_balance, // 余额支付金额
            ];
        }
        $order_pay_model = new OrderPay();

        try {
            $order_pay_info = $order_pay_model->create($create_data);
        } catch (\Exception $e) {
            Log::channel('qwlog')->debug($e->getMessage());
            return $this->format_error(__('orders.payment_failed'));
        }

        return $this->format($order_pay_info);

    }

    /**
     * 2021/3/11--10:54
     * @param $params
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:createOrderFormat
     * @effect:格式化订单信息
     */
    public function createOrderFormat($params, $is_valuation = false, $is_default = false, $is_return_price = true)
    {
        $goods_model = new Goods();


        $goods_sku_model = new GoodsSku();
        $list = [];
        $before_list = [];
        $valuation_price = [];
        $this->cartId = []; // 购物车ID 初始化
        foreach ($params['order'] as $v) {
            $data = $goods_model->with(['store' => function ($q) {
                return $q->select('id', 'store_name', 'store_logo', 'class_id', 'community_id');
            }])->select('id', 'store_id', 'goods_name', 'goods_market_price', 'goods_master_image', 'goods_price', 'goods_stock', 'goods_weight', 'freight_id')->where('id', $v['goods_id'])->first()->toArray();
            $data['sku_name'] = '-';
            $data['buy_num'] = abs(intval($v['buy_num']));
            $data['sku_id'] = $v['sku_id'];
            if ($v['sku_id'] > 0) {
                $goods_sku = $goods_sku_model->select('id', 'sku_name', 'goods_market_price', 'goods_price', 'goods_stock', 'goods_weight')->where('goods_id', $v['goods_id'])->where('id', $v['sku_id'])->first();
                $data['sku_name'] = $goods_sku['sku_name'];
                $data['goods_market_price'] = $goods_sku['goods_market_price'];
                $data['goods_price'] = $goods_sku['goods_price'];
                $data['goods_stock'] = $goods_sku['goods_stock'];
                $data['goods_weight'] = $goods_sku['goods_weight'];
            }

            $data['goods_master_image'] = $this->thumb($data['goods_master_image'], 150);
            // 商品总价
            $data['total'] = round($v['buy_num'] * $data['goods_price'], 2);
            // 商品总重量
            $data['total_weight'] = round($v['buy_num'] * $data['goods_weight'], 2);
            if (!empty($v['ifcart'])) {
                $data['cart_id'] = $v['cart_id'];
            }
            $list[$data['store']['id']]['goods_list'][] = $data;
            $list[$data['store']['id']]['store_info'] = $data['store'];


            $before_list['info'][$data['store']['id']] = $list[$data['store']['id']]['store_info'];
            $before_list['info'][$data['store']['id']]['goods_list'] = $list[$data['store']['id']]['goods_list'];
            if (empty($list[$data['store']['id']]['store_total_price'])) {
                $list[$data['store']['id']]['store_total_price'] = 0;
            }
            $list[$data['store']['id']]['store_total_price'] += $data['total'];


            // 判断是否库存足够
            if ($v['buy_num'] > $data['goods_stock']) {
                return $this->format_error(__('orders.stock_error'));
            }
            // 判断是否是购物车
            if (!empty($params['ifcart'])) {
                $this->cartId[] = $v['cart_id'];
            }

            if ($is_valuation == true) {
                $valuation_price [] = [
                    'total' => round($v['buy_num'] * $data['goods_price'], 2),
                    'total_weight' => round($v['buy_num'] * $data['goods_weight'], 2),
                    'store_id' => $data['store']['id'],
                    'store_cate_id' => $data['store']['class_id'],
                    'freight_id' => $data['freight_id']
                ];
            }

        }

        if ($is_valuation !== false) {
            $address_info = [];
            if ($is_default) {
                $address_info = $this->addressService->getDefault()['data'];
            }
            // 计算金额
            $price = $this->valuation($valuation_price, $address_info);
            //总金额
            $before_list['total_price'] = $price['total_price'];
            //优惠金额
            $before_list['discount_price'] = $price['discount_price'];
            //运费金额
            $before_list['freight_money'] = $price['freight_money'];
            //积分抵扣金额
            $before_list['integral_ratio_price'] = $price['integral_ratio_price'];
        } else {
            $before_list = array_merge($before_list, []);
        }
        if (request()->address_id) {
            $before_list['default_address'] = $this->addressService->getAddresses(request()->address_id)['data'];
        }
        if ($is_valuation == true && $is_default == true) {
            return $this->format($before_list);
        } else if ($is_return_price) {
            return $this->format($price);
        } else {
            return $this->format($list);
        }
    }


    /**
     * 2021/3/11--11:26
     * @param array $data 商品信息
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:valuation
     * @effect: 订单计价
     */
    public function valuation($data, $address_info)
    {
        $full_reduction_service = new FullReductionService();
        //订单总价
        $finally_total_price = 0;
        //订单运费金额
        $finally_freight_money = 0;
        //订单优惠金额
        $finally_discount_price = 0;
        //订单积分抵扣金额
        $integral_ratio_price = 0;
        foreach ($data as $k => $v) {

            $total_price = 0;                                                                                                                                                                                                                                                                                                                                                                                                                           // 总金额
            $order_price = 0;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               // 订单总金额
            $total_weight = 0;                                                                                                                                                                                                                                                                                                                  // 总重量
            $freight_money = 0;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               // 运费
            $discount_price = 0; // 优惠券 金额
            $integral_price = 0;
            // 将商品总总量加起来
            $total_weight += $v['total_weight'];
            // 将金额全部计算加载到订单里面
            $order_price += $v['total'];
            // 满减
            $full_reduction_resp = $full_reduction_service->getFullReductionInfoByStoreId($v['store_id'], ($order_price + $freight_money));
            if ($full_reduction_resp['status']) {
                $discount_price += $full_reduction_resp['data']['money'];
            }
            if (!empty($address_info)) {
                // 直接计算运费，如果多个不同的商品取第一个商品的运费
                $freight_money = $this->sumFreight($v['freight_id'], $total_weight, $v['store_id'], $address_info['province_id']);
            }
            $integral_discount_price = 0.00;
            extract($this->integral_discount($v['store_id'], 1, $v['store_cate_id']), EXTR_OVERWRITE);
            // 获取积分抵扣金额
            $integral_price += $integral_discount_price;
            // 暂时总金额等于[订单金额+运费-优惠金额-积分抵扣]
            // 订单总金额做修改，然后保存
            $total_price = $order_price + $freight_money - $discount_price - $integral_price;
            //总价格
            $finally_total_price += $total_price;
            //运费金额
            $finally_freight_money += $freight_money;
            //优惠金额
            $finally_discount_price += $discount_price;
            //积分金额
            $integral_ratio_price += $integral_price;
        }
        return [
            'total_price' => round($finally_total_price, 2),
            'freight_money' => $finally_freight_money,
            'discount_price' => $finally_discount_price,
            'integral_ratio_price' => $integral_ratio_price,
        ];
    }

    /**
     * 2021/3/15--15:15
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:get_integral
     * @effect:奖励积分
     */
    public function get_integral($store_id, $store_cate_id, $scenes_type)
    {
        // 积分获取
        return $this->integralService->get_integral($store_id, $store_cate_id, $scenes_type);
    }

    /**
     * 2021/3/15--15:01
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:integral_discount
     * @effect:积分优惠金额
     */
    public function integral_discount($store_id, $scenes_type, $store_cate_id)
    {
        // 获取实际用到的 积分比例设置
        $ratio_set = $this->integralService->getOne($store_id, $scenes_type, $store_cate_id);
        // 优惠金额
        $discount_price = 0.00;
        //使用积分
        $integral = 0.00;
        if (!empty($ratio_set)) {
            $user_service = new UserService;
            $user_info = $user_service->getUserInfo();
            // 假设有 100 积分
            $int = $user_info->integral;
            //假设 1 积分 抵扣 0.01
            $ratio = $ratio_set['ratio'];
            // 假设  当前比例上限
            $integral_upper_limit = $ratio_set['integral_upper_limit'];
            $discount_price = $int * $ratio;
            $integral = $int;
            // 如果超过上限则用上限去计算优惠金额
            if ($int > $integral_upper_limit) {
                $integral = $integral_upper_limit;
                $discount_price = $integral_upper_limit * $ratio;
            }
        }
        // 积分抵扣金额
        return [
            'integral_discount_price' => $discount_price,
            'use_integral' => $integral
        ];
    }


    /**
     * 2021/3/11--10:56
     * @param $goods_id
     * @param $num
     * @param int $is_type
     * @throws \Exception
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:orderSale
     * @effect:订单销量
     */
    public function orderSale($goods_id, $num, $is_type = 0)
    {

        try {

            $goods_model = new Goods;
            if (empty($is_type)) {
                $goods_model->where('id', $goods_id)->decrement('goods_sale', $num);
            } else {
                $goods_model->where('id', $goods_id)->increment('goods_sale', $num);
            }
        } catch (\Exception $e) {
            throw new \Exception(__('base.error') . ' - stock');
        }

    }

    /**
     * 2021/3/11--10:57
     * @param $goods_id
     * @param $sku_id
     * @param $num
     * @param int $is_type 0 =减少 1=增加
     * @throws \Exception
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:orderStock
     * @effect:订单库存
     */
    public function orderStock($goods_id, $sku_id, $num, $is_type = 0)
    {

        try {
            if (empty($sku_id)) {
                $goods_model = new Goods;
                if (empty($is_type)) {
                    $goods_model->where('id', $goods_id)->decrement('goods_stock', $num);
                } else {
                    $goods_model->where('id', $goods_id)->increment('goods_stock', $num);
                }
            } else {
                $goods_sku_model = new GoodsSku();
                if (empty($is_type)) {
                    $goods_sku_model->where('id', $sku_id)->decrement('goods_stock', $num);
                } else {
                    $goods_sku_model->where('id', $sku_id)->increment('goods_stock', $num);
                }
            }
        } catch (\Exception $e) {
            throw new \Exception(__('base.error') . ' - stock');
        }

    }

    /**
     * 2021/3/11--10:57
     * @throws \Exception
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:delCart
     * @effect:购物车删除
     */
    private function delCart()
    {
        if (!empty($this->cartId)) {
            $cart_model = new Cart();
            try {
                $cart_model->whereIn('id', $this->cartId)->delete();
            } catch (\Exception $e) {
                throw new \Exception(__('orders.order_cart_del_error'));
            }
        }
    }

    /**
     * 2021/3/11--10:59
     * @param $params
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:CalculatePrice
     * @effect:订单价格计算
     */
    public function CalculatePrice($params)
    {

        $data = $this->createOrderFormat($params, true, false, true)['data'];
        $data = [
            'total_price' => $data['total_price'],  //实际支付价格
            'coupon_money' => $data['discount_price'], // 优惠价格
//            'goods_market_price' => (int)$goods_market_price //市场价格
        ];
        return $this->format($data);
    }

    /**
     * 2021/3/11--9:55
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:createOrderBefore
     * @effect:订单创建之前处理
     */
    public function createOrderBefore()
    {
        $params['order'] = json_decode(request()->order, true);
        $rs = $this->createOrderFormat($params, true, true);
        return $rs['status'] ? $this->format($rs['data']) : $this->format_error($rs['msg']);
    }

    /**
     * 2021/3/11--10:58
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:createOrderAfter
     * @effect:订单创建后
     */
    public function createOrderAfter()
    {
        $check = $this->base64Check();
        if (!$check['status']) {
            return $this->format_error($check['msg']);
        }
        $params = $check['data'];
        $order_model = new Order;
        $list = $order_model->whereIn('id', $params['order_id'])->with('order_goods')->get();

        return $this->format(new CreateOrderAfterCollection($list));
    }
//------------------------------------------------------------------------订单信息相关------------------------------------//

    /**
     * 2021/3/11--10:50
     * @param $order_info
     * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Translation\Translator|string
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getOrderStatusCn
     * @effect:获取订单状态
     */
    public function getOrderStatusCn($order_info)
    {
        $cn = '未知订单';
        switch ($order_info['order_status']) {
            case 0:
                $cn = __('admins.order_cancel');
                break;
            case 1:
                $cn = __('admins.wait_pay');
                break;
            case 2:
                $cn = __('admins.wait_send');
                break;
            case 3:
                $cn = __('admins.order_confirm');
                break;
            case 4:
                $cn = __('admins.wait_comment');
                break;
            case 5:
                if ($order_info['refund_type'] == 0) {
                    $cn = __('admins.order_refund');
                } elseif ($order_info['refund_type'] == 1) {
                    $cn = __('admins.order_returned');
                } else {
                    $cn = __('admins.order_refund_over');
                }

                break;
            case 6:
                $cn = __('admins.order_completion');
                break;
        }
        return $cn;
    }

    /**
     * 2021/3/11--10:50
     * @param $payment_name
     * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Translation\Translator|string
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getOrderPayMentCn
     * @effect:获取订单支付类型
     */
    public function getOrderPayMentCn($payment_name)
    {
        $cn = '未支付';
        switch ($payment_name) {
            case 'wechat':
                $cn = __('admins.payment_wechat');
                break;
            case 'ali':
                $cn = __('admins.payment_ali');
                break;
            case 'money':
                $cn = __('admins.payment_money');
                break;
        }
        return $cn;
    }

    /**
     * 2021/3/11--10:51
     * @param $id
     * @param string $auth
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getOrderInfoById
     * @effect:获取订单信息
     */
    public function getOrderInfoById($id, $auth = 'user')
    {
        $order_model = new Order();

        if ($auth == 'user') {
            $user_service = new UserService;
            $user_info = $user_service->getUserInfo();
            $order_model = $order_model->where('user_id', $user_info['id']);
        }

        if ($auth == 'seller') {
            $store_id = $this->get_store(true);
            $order_model = $order_model->where('store_id', $store_id);
        }

        $order_info = $order_model->with('order_goods')->with(['store' => function ($query) {
            return $query->select('id', 'store_name', 'store_logo', 'refund_name', 'refund_phone', 'refund_address');
        }])->where('id', $id)->first();
        return $this->format($order_info);
    }

    /**
     * 2021/3/11--10:52
     * @param string $type
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getOrders
     * @effect:获取订单列表
     */
    public function getOrders($type = "user")
    {
        $order_model = new Order();

        if ($type == 'user') {
            $user_service = new UserService;
            $user_info = $user_service->getUserInfo();
            $order_model = $order_model->where('user_id', $user_info['id']);
        }
        if ($type == 'seller') {
            $store_id = $this->get_store(true);
            $order_model = $order_model->where('store_id', $store_id);
        }


        $order_model = $order_model->with(['store' => function ($q) {
            return $q->select('id', 'store_name', 'store_logo');
        }, 'user' => function ($q) {
            return $q->select('id', 'username');
        }, 'order_goods']);


        // 订单号
        $order_no = request()->order_no;
        if (!empty($order_no)) {
            $order_model = $order_model->where('order_no', 'like', '%' . $order_no . '%');
        }

        // 拼团订单ID查询
        $collective_id = request()->collective_id;
        if (!empty($collective_id)) {
            $order_model = $order_model->where('collective_id', $collective_id);
        }

        // 用户ID
        $user_id = request()->user_id;
        if (!empty($user_id)) {
            $order_model = $order_model->where('user_id', $user_id);
        }

        // 店铺ID
        $store_id = request()->store_id;
        if (!empty($store_id)) {
            $order_model = $order_model->where('store_id', $store_id);
        }

        // 下单时间
        $created_at = request()->created_at;
        if (!empty($created_at)) {
            $order_model = $order_model->whereBetween('created_at', [$created_at[0], $created_at[1]]);
        }

        // 订单状态
        if (isset(request()->order_status)) {
            $order_model = $order_model->where('order_status', request()->order_status);
        }

        // 获取售后订单
        if (isset(request()->is_refund)) {
            $order_model = $order_model->where('order_status', 5);
        }

//        // 获取退货订单
//        if (isset(request()->is_return)) {
//            $order_model = $order_model->where('order_status', 5)->where('refund_status', 1);
//        }

        $refund_model = new Refund();
        //排除软删除
        $order_model = $order_model->where('deleted_at', 0);

        $order_model = $order_model->orderBy('id', 'desc');

        if ($type == 'seller' || $type == 'admin') {
            $order_model = $order_model->paginate($request->per_page ?? 30);
        } else {
            $order_model = $order_model->get()->toArray();
        }


        if (isset(request()->is_refund)) {
            foreach ($order_model as $key => $v) {
                $order_model[$key]['refund_info'] = $refund_model->where('order_id', $v['id'])->first();
            }
        }
        return $this->format($order_model);
    }


    /**
     * 2021/3/12--19:21
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:delete
     * @effect:订单软删除
     */
    public function delete()
    {
        $order_model = new Order();
        $id = request()->order_id;
        try {
            $res = $order_model->where('id', $id);
            $res->update(
                ['deleted_at' => time()]
            );
            return $this->format([]);
        } catch (\Exception $e) {
            return $this->format_error('删除失败' . $e->getMessage());
        }
    }
//--------------------------------------------------------------------------验证----------------------------------------//

    /**
     * 2021/3/11--10:48
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:checkAddress
     * @effect:验证用户地址是否存在
     */
    public function checkAddress()
    {
        $id = request()->address_id ?? 0;
        if (empty($id)) {
            return $this->format_error(__('orders.no_address'));
        }

        $address_model = new Address();
        $address_info = $address_model->find($id);

        if (empty($address_info)) {
            return $this->format_error(__('orders.no_address') . '2');
        }

        return $this->format($address_info);
    }

    /**
     * 2021/3/11--10:52
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:base64Check
     * @effect:传参验证
     */
    /*    public function base64Check()
    {
        $base64 = request()->params ?? '';
        // 如果为空
        if (empty($base64)) {
            return $this->format_error(_('orders.error'));
        }

        // 判断是否能解析
        try {
            $params = json_decode(base64_decode($base64), true);
        } catch (\Exception $e) {
            return $this->format_error(_('orders.error') . '2');
        }
        return $this->format($params);
    }*/

//-------------------------------------------------------------------------计价------------------------------------------//

    /**
     * 2021/3/11--10:48
     * @param $freight_id 运费模版
     * @param $total_weight 总重量
     * @param $store_id 店铺ID
     * @param $area_id 省份ID
     * @return float|int
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:sumFreight
     * @effect: 运费计价
     */
    protected function sumFreight($freight_id, $total_weight, $store_id, $area_id)
    {
        $freight_model = new Freight();
        $default_info = $freight_model->where('is_type', 0)->where('store_id', $store_id)->first(); // 默认快递模版
        if ($freight_id == 0) { // 默认模版
            $info = $default_info;
        } else {
            $info = $freight_model->find($freight_id);
        }

        if (empty($info) || ($info->f_weight == 0 && $info->f_price == 0)) {
            return 0;
        }

        $area = [];
        if (!empty($info->area_id)) {
            $area = explode(',', $info->area_id);
        }
        // 如果配送地址不存在 商家配置的地址则走默认的
        if (!in_array($area_id, $area)) {
            $info = $default_info;
        }

        // 如果没有设置则为0
        if ($info->f_weight == 0 && $info->f_price == 0) {
            return 0;
        }

        // 如果设置了运费，没设置重量则代表无限重量 同一运费
        if ($info->f_weight == 0 && $info->f_price > 0) {
            return $info->f_price;
        }

        // 如果首重和首价格设置了
        if (($info->f_weight > 0 && $info->f_price > 0)) {
            // 判断是否重量有超过
            if ($info->f_weight >= $total_weight) {
                return $info->f_price;
            } else {
                // 超过了则开始分析是否有超出另外计价
                if ($info->o_weight == 0 && $info->o_price == 0) {
                    return $info->f_price;
                }
                // 超过了则开始分析是否有配置超出另外计价
                if ($info->o_weight == 0 && $info->o_price == 0) {
                    return $info->f_price;
                }
                // 超过了则开始分析是否有超出另外计价
                if ($info->o_weight > 0) {
                    $o_num = ceil(($total_weight - $info->f_weight) / $info->o_weight); // 超出的倍数
                    return round($info->f_price + ($o_num * $info->o_price), 2);
                }
            }
        }

        return 0;

    }


    /**
     * 2021/3/16--11:08
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getModel
     * @effect:获取订单模型
     */
    public function getModel()
    {
        return new Order();
    }


    /**
     * 2021/3/18--19:51
     * @param $community_id  小区ID
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getFreight
     * @effect:获取运费
     */
    public function getFreight($community_id)
    {
        $community_service = new CommunityService();
        $property_model = new Property();
        $property_id = $community_service->getEstateId($community_id);
        $info = $property_model->where('id', $property_id)->first();
        return $info['shipping'];
    }

    /**
     * 2021/3/22--3:23 下午
     * @param $community_id
     * @return mixed
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @effect:获取结算时间
     */
    public function getSettlementTime($community_id)
    {
        $community_service = new CommunityService();
        $property_model = new Property();
        $property_id = $community_service->getEstateId($community_id);
        $info = $property_model->where('id', $property_id)->first();
        return $info['settlement_time'];
    }
}
